package com.homedo.odin.solution.service.bizservice.pc;

import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.dto.ResultData;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.odin.solution.contract.pc.EarningReq;
import com.homedo.odin.solution.contract.pc.PayCallBackResponseBean;
import com.homedo.odin.solution.contract.pc.PaymentResponseBean;
import com.homedo.odin.solution.contract.pc.UserOrderResponseBean;
import com.homedo.odin.solution.contract.pc.UserPayOrderRequestBean;
import com.homedo.odin.solution.contract.pc.UserPayRequestBean;
import com.homedo.odin.solution.contract.personal.userhomepage.AddPopularityReq;
import com.homedo.odin.solution.enumcode.TemplateCodeEnum;
import com.homedo.odin.solution.enumcode.basic.BusinessTypeEnum;
import com.homedo.odin.solution.enumcode.basic.DownloadCollectEnum;
import com.homedo.odin.solution.enumcode.hebi.HebiOrderBizTypeEnum;
import com.homedo.odin.solution.enumcode.other.PopularityEnum;
import com.homedo.odin.solution.enumcode.pay.ReturnCode;
import com.homedo.odin.solution.enumcode.solution.SolutionStateEnum;
import com.homedo.odin.solution.enumcode.specification.SpecificationStatus;
import com.homedo.odin.solution.enumcode.user.PayModeEnum;
import com.homedo.odin.solution.enumcode.user.PayStateEnum;
import com.homedo.odin.solution.model.base.MReturn;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.Specification;
import com.homedo.odin.solution.model.entity.UserPayOrder;
import com.homedo.odin.solution.model.entity.UserSolution;
import com.homedo.odin.solution.model.entity.UserSpecification;
import com.homedo.odin.solution.service.SmsServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.SpecificationServiceImpl;
import com.homedo.odin.solution.service.UserPayOrderServiceImpl;
import com.homedo.odin.solution.service.UserSolutionServiceImpl;
import com.homedo.odin.solution.service.UserSpecificationServiceImpl;
import com.homedo.odin.solution.service.bizservice.personal.CommonBizService;
import com.homedo.odin.solution.service.common.PaymentService;
import com.homedo.odin.solution.service.common.WalletService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: zhaoxudong
 * @date: 2018/4/11 16:38
 * @Description:
 */
@Service
public class PayBizService {

    private static final Logger logger = LoggerFactory.getLogger(PayBizService.class);
    @Autowired
    UserPayOrderServiceImpl userPayOrderService;
    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    WalletService walletService;
    @Autowired
    CommonBizService commonBizService;
    @Autowired
    SmsServiceImpl smsServiceImpl;
    @Autowired
    UserSolutionServiceImpl userSolutionService;
    @Autowired
    SpecificationServiceImpl specificationService;
    @Autowired
    UserSpecificationServiceImpl userSpecificationService;
    @Autowired
    PaymentService paymentService;

    public MReturn<Long> payCallBack(Boolean isVerify, BigDecimal amount, String outTradeNo, String tradeNo,
            String payBackData, String orderIds) {
        try {
            logger.info(String.format("%s param:%s", "支付返回的所有信息", payBackData));
            UserPayOrder order = userPayOrderService.getPayOrderByOrderNo(Long.valueOf(orderIds));
            if (order == null) {
                return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(),
                        Long.parseLong(orderIds));
            }
            if (BusinessTypeEnum.SOLUTION.getDbValue() == order.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(order.getBusinessId());
                if (solution == null) {
                    return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(), order.getOrderNo());
                }
                if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                    //订单存在且已经支付成功
                    return new MReturn<Long>(Boolean.TRUE, "处理成功", ReturnCode.SUCCEED.getValue(),
                            solution.getSolutionId());
                }
                if (isVerify) {//支付成功

                    /**更新支付流水中的状态值*/
                    userPayOrderService.updateOrderStatus(order.getOrderNo(), PayStateEnum.PAYCOMPLETE.getDbValue());
                    //增加用户账户金额
                    if (NumberHelper.validatePositive(solution.getUserId()) || NumberHelper
                            .validatePositive(solution.getExpertId())) {
                        Map<String, String> map = new HashMap<>();
                        if (NumberHelper.validatePositive(solution.getUserId())) {
                            map.put("accountId", solution.getUserId() + "");
                        } else {
                            map.put("accountId", solution.getExpertId() + "");
                        }
                        map.put("walletType", "1");
                        //曝光类型为精品，获得下载收费金额的50% ,常规50%
                        BigDecimal walletAmount = new BigDecimal(0);
                        if (solution.getExpType().intValue() == 1) {
                            walletAmount = solution.getCharges().multiply(new BigDecimal(0.5));
                        } else if (solution.getExpType().intValue() == 2) {
                            walletAmount = solution.getCharges().multiply(new BigDecimal(0.5));
                        }
                        map.put("amount", walletAmount.toString());
                        map.put("bizFrom", "15");
                        map.put("bizOrderCode", solution.getSolutionId().toString());
                        map.put("inOut", "1");
                        map.put("payType", "3");
                        map.put("note", solution.getSolutionName());
                        //钱包功能已去掉
                        //walletService.addWalletBalance(map);

                        //hebi 返还
                        EarningReq hebiEarningDo = new EarningReq();
                        hebiEarningDo.setBizId(solution.getSolutionId().toString());
                        hebiEarningDo.setBizType(HebiOrderBizTypeEnum.SOLUTION.getDbValue());
                        hebiEarningDo.setHebiAmount(solution
                                .getCharges().multiply(new BigDecimal(50)));
                        hebiEarningDo.setPublishUserId(solution.getUserId());
                        hebiEarningDo.setUserId(order.getUid());
                        commonBizService.earning(hebiEarningDo);
                        //发短信
                        smsServiceImpl.sendDownloadSolutionSMS(solution);
                        //专家用户分成
                    }
                    //增加下载记录
                    UserSolution userSolution = userSolutionService
                            .getUserSolution(order.getUid(), order.getBusinessId(),
                                    DownloadCollectEnum.DOWNLOAD.getDbValue());
                    //userSolution表中存在记录,则只新增下载量,否则还需插入下载记录
                    if (userSolution == null) {
                        //插入下载记录
                        UserSolution uSolution = new UserSolution();
                        uSolution.setCreateTime(new Date());
                        uSolution.setUserId(order.getUid());
                        uSolution.setSolutionId(order.getBusinessId());
                        uSolution.setActionType(DownloadCollectEnum.DOWNLOAD.getDbValue());
                        userSolutionService.addUserSolution(uSolution);

                        //发送通知

                        Map<String, String> paramMap = com.google.common.collect.Maps.newHashMap();
                        paramMap.put("@@userName", solution.getUserName());
                        paramMap.put("@@bizId", solution.getSolutionId().toString());
                        paramMap.put("@@solution", solution.getSolutionName());
                        paramMap.put("@@money", solution.getCharges().multiply(new BigDecimal(50)).toString());
                        commonBizService.sentMessage(paramMap, solution.getUserId(), order.getUid(),
                                TemplateCodeEnum.solution_down.toString());
                        //增加人气
                        AddPopularityReq req = new AddPopularityReq();
                        req.setOperationId(order.getUid());
                        req.setTargetId(solution.getUserId());
                        req.setType(PopularityEnum.Download.getType());
                        commonBizService.addPopularity(req);
                    }

                    //新增下载量
                    solutionService.addSolutionDownload(order.getBusinessId());
                    return new MReturn<Long>(Boolean.TRUE, "处理成功", ReturnCode.SUCCEED.getValue(),
                            solution.getSolutionId());
                } else {
                    return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(), null);
                }
                //行业规范
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == order.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(order.getBusinessId());
                if (specification == null) {
                    return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(), order.getOrderNo());
                }
                if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                    //订单存在且已经支付成功
                    return new MReturn<Long>(Boolean.TRUE, "处理成功", ReturnCode.SUCCEED.getValue(),
                            specification.getSpecificationId());
                }
                if (isVerify) {//支付成功

                    /**更新支付流水中的状态值*/
                    userPayOrderService.updateOrderStatus(order.getOrderNo(), PayStateEnum.PAYCOMPLETE.getDbValue());
                    //增加用户账户金额
                    if (NumberHelper.validatePositive(specification.getUserId())) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("accountId", specification.getUserId() + "");
                        map.put("walletType", "1");
                        //曝光类型为精品，获得下载收费金额的50% ,常规50%
                        BigDecimal walletAmount = specification.getCharges().multiply(new BigDecimal(0.5));
                        map.put("amount", walletAmount.toString());
                        map.put("bizFrom", "16");
                        map.put("bizOrderCode", specification.getSpecificationId().toString());
                        map.put("inOut", "1");
                        map.put("payType", "3");
                        map.put("note", specification.getSpecificationName());
                        //钱包功能已去掉
                        //walletService.addWalletBalance(map);
                        //增加短信提醒
                        //TODO
                        //专家用户分成
                    }
                    //增加下载记录
                    UserSpecification userSpecification = userSpecificationService
                            .getUserSpecification(order.getUid(), order.getBusinessId(),
                                    DownloadCollectEnum.DOWNLOAD.getDbValue());
                    //userSolution表中存在记录,则只新增下载量,否则还需插入下载记录
                    if (userSpecification == null) {
                        //插入下载记录
                        UserSpecification uSpecification = new UserSpecification();
                        uSpecification.setCreateTime(new Date());
                        uSpecification.setUserId(order.getUid());
                        uSpecification.setSpecificationId(order.getBusinessId());
                        uSpecification.setActionType(DownloadCollectEnum.DOWNLOAD.getDbValue());
                        userSpecificationService.addUserSpecification(uSpecification);
                    }
                    //新增下载量
                    specificationService.addSpecificationDownload(order.getBusinessId());
                    return new MReturn<Long>(Boolean.TRUE, "处理成功", ReturnCode.SUCCEED.getValue(),
                            specification.getSpecificationId());
                } else {
                    return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(), null);
                }
                //其他
            } else {
                return new MReturn<Long>(Boolean.FALSE, "处理失败", ReturnCode.FAILURE.getValue(), null);
            }

        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "payCallBack");
            e.printStackTrace();
            logger.error(errMsg, e);
            return new MReturn<Long>(Boolean.FALSE, errMsg, ReturnCode.FAILURE.getValue(), null);
        }
    }

    public ResultData pcPayCallBack(Integer uid, String tradeNo) {
        try {
            UserPayOrder userPayOrder = userPayOrderService.getPayOrderByOrderNo(Long.valueOf(tradeNo));
            if (userPayOrder == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "支付订单不存在！"), null);
            }
            PayCallBackResponseBean callBackBean = new PayCallBackResponseBean();
            if (BusinessTypeEnum.SOLUTION.getDbValue() == userPayOrder.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(userPayOrder.getBusinessId());
                if (solution == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }

                callBackBean.setAmout(userPayOrder.getAmount());
                callBackBean.setDealTime(userPayOrder.getCreateTime());
                callBackBean.setPayTypeName(PayModeEnum.getExistDisplayValue(userPayOrder.getPayMode()));
                callBackBean.setTradeNo(userPayOrder.getOrderNo().toString());
                callBackBean
                        .setIsOk(PayStateEnum.PAYCOMPLETE.getDbValue().equals(userPayOrder.getStatus()) ? true : false);
                callBackBean.setBusinessId(userPayOrder.getBusinessId());
                callBackBean.setBusinessType(userPayOrder.getBusinessType());
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == userPayOrder.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(userPayOrder.getBusinessId());
                if (specification == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }
                callBackBean.setAmout(userPayOrder.getAmount());
                callBackBean.setDealTime(userPayOrder.getCreateTime());
                callBackBean.setPayTypeName(PayModeEnum.getExistDisplayValue(userPayOrder.getPayMode()));
                callBackBean.setTradeNo(userPayOrder.getOrderNo().toString());
                callBackBean
                        .setIsOk(PayStateEnum.PAYCOMPLETE.getDbValue().equals(userPayOrder.getStatus()) ? true : false);
                callBackBean.setBusinessId(userPayOrder.getBusinessId());
                callBackBean.setBusinessType(userPayOrder.getBusinessType());
            }
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "返回信息成功！"), callBackBean);
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "pc-CallBack");
            e.printStackTrace();
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), "返回信息成功！"), null);
        }
    }

    public ResultData aliPay(UserPayRequestBean userPayRequestBean) {
        if (userPayRequestBean == null) {
            return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
        }
        try {
            logger.info(String.format("%s param:%s", "aliPay", userPayRequestBean.toJson()));
            if (StringUtils.isEmpty(userPayRequestBean.getTradeNo()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getPayMode()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
            }
            UserPayOrder order = userPayOrderService
                    .getPayOrderByOrderNo(Long.valueOf(userPayRequestBean.getTradeNo()));
            if (order == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单不存在！"), null);
            }
            if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单已支付！"), null);
            }
            if (!order.getUid().equals(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户不是该订单用户！"), null);
            }
            String subject = null;
            String body = null;
            if (BusinessTypeEnum.SOLUTION.getDbValue() == order.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(order.getBusinessId());
                if (solution == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }
                if (solution.getStatus().intValue() != SolutionStateEnum.SHELVE.getDbValue()) {
                    return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该方案不是上架状态！"), null);
                }
//				if(SOLUTION.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == order.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(order.getBusinessId());
                if (specification == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范不存在！"), null);
                }
                if (specification.getStatus().intValue() != SpecificationStatus.SHELVE.getDbValue()) {
                    return ResultData
                            .newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该行业规范不是上架状态！"), null);
                }
//				if(specification.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else {
                return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "订单信息不正确！"), null);
            }
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("OrderIds", userPayRequestBean.getTradeNo());
            paraMap.put("Amount", order.getAmount().toString());
            paraMap.put("Type", userPayRequestBean.getPayMode() + "");
            paraMap.put("AccountId", order.getUid() + "");
            paraMap.put("OperatorId", order.getUid() + "");
            paraMap.put("Subject", subject);
            paraMap.put("Body", body);
            userPayOrderService.updatePayModel(order.getOrderNo(), userPayRequestBean.getPayMode());

            String resultJson = paymentService.aliPayPc(paraMap);
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "返回支付信息成功"),
                    new PaymentResponseBean(resultJson, paraMap.get("OrderIds")));
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "aliPay");
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), errMsg), null);
        }
    }

    public ResultData unionPayB2C(UserPayRequestBean userPayRequestBean) {
        try {
            if (userPayRequestBean == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
            }
            logger.info(String.format("%s param:%s", "unionPayB2B", userPayRequestBean.toJson()));
            if (StringUtils.isEmpty(userPayRequestBean.getTradeNo()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getPayMode()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
            }
            UserPayOrder order = userPayOrderService
                    .getPayOrderByOrderNo(Long.valueOf(userPayRequestBean.getTradeNo()));
            if (order == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单不存在！"), null);
            }
            if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单已支付！"), null);
            }
            if (!order.getUid().equals(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户不是该订单用户！"), null);
            }
            String subject = null;
            String body = null;
            if (BusinessTypeEnum.SOLUTION.getDbValue() == order.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(order.getBusinessId());
                if (solution == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }
                if (solution.getStatus().intValue() != SolutionStateEnum.SHELVE.getDbValue()) {
                    return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该方案不是上架状态！"), null);
                }
//				if(SOLUTION.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == order.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(order.getBusinessId());
                if (specification == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范不存在！"), null);
                }
                if (specification.getStatus().intValue() != SpecificationStatus.SHELVE.getDbValue()) {
                    return ResultData
                            .newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该行业规范不是上架状态！"), null);
                }
//				if(specification.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else {
                return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "订单信息不正确！"), null);
            }
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("OrderIds", userPayRequestBean.getTradeNo());
            paraMap.put("Amount", order.getAmount().toString());
            paraMap.put("Type", userPayRequestBean.getPayMode() + "");
            paraMap.put("AccountId", order.getUid() + "");
            paraMap.put("OperatorId", order.getUid() + "");
            paraMap.put("Subject", subject);
            paraMap.put("Body", body);
            userPayOrderService.updatePayModel(order.getOrderNo(), userPayRequestBean.getPayMode());

            String resultJson = paymentService.unionPayB2CPc(paraMap);
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "返回银联支付信息成功！"),
                    new PaymentResponseBean(resultJson, paraMap.get("OrderIds")));
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "unionPay");
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), errMsg), null);
        }
    }

    public ResultData unionPayB2B(UserPayRequestBean userPayRequestBean) {
        if (userPayRequestBean == null) {
            return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
        }
        try {
            logger.info(String.format("%s param:%s", "unionPayB2B", userPayRequestBean.toJson()));
            if (StringUtils.isEmpty(userPayRequestBean.getTradeNo()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getPayMode()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
            }
            UserPayOrder order = userPayOrderService
                    .getPayOrderByOrderNo(Long.valueOf(userPayRequestBean.getTradeNo()));
            if (order == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单不存在！"), null);
            }
            if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单已支付！"), null);
            }
            if (!order.getUid().equals(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户不是该订单用户！"), null);
            }
            String subject = null;
            String body = null;
            if (BusinessTypeEnum.SOLUTION.getDbValue() == order.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(order.getBusinessId());
                if (solution == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }
                if (solution.getStatus().intValue() != SolutionStateEnum.SHELVE.getDbValue()) {
                    return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该方案不是上架状态！"), null);
                }
//				if(SOLUTION.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == order.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(order.getBusinessId());
                if (specification == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范不存在！"), null);
                }
                if (specification.getStatus().intValue() != SpecificationStatus.SHELVE.getDbValue()) {
                    return ResultData
                            .newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该行业规范不是上架状态！"), null);
                }
//				if(specification.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else {
                return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "订单信息不正确！"), null);
            }
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("OrderIds", userPayRequestBean.getTradeNo());
            paraMap.put("Amount", order.getAmount().toString());
            paraMap.put("Type", userPayRequestBean.getPayMode() + "");
            paraMap.put("AccountId", order.getUid() + "");
            paraMap.put("OperatorId", order.getUid() + "");
            paraMap.put("Subject", subject);
            paraMap.put("Body", body);
            userPayOrderService.updatePayModel(order.getOrderNo(), userPayRequestBean.getPayMode());

            String resultJson = paymentService.unionPayB2BPc(paraMap);
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "返回银联支付信息成功！"),
                    new PaymentResponseBean(resultJson, paraMap.get("OrderIds")));
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "unionPay");
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), errMsg), null);
        }
    }

    public ResultData wxPay(UserPayRequestBean userPayRequestBean) {
        if (userPayRequestBean == null) {
            return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
        }
        try {
            logger.info(String.format("%s param:%s", "wxPay", userPayRequestBean.toJson()));
            if (StringUtils.isEmpty(userPayRequestBean.getTradeNo()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getPayMode()) ||
                    !NumberHelper.validatePositive(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数错误！"), null);
            }
            UserPayOrder order = userPayOrderService
                    .getPayOrderByOrderNo(Long.valueOf(userPayRequestBean.getTradeNo()));
            if (order == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单不存在！"), null);
            }
            if (order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "订单已支付！"), null);
            }
            if (!order.getUid().equals(userPayRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户不是该订单用户！"), null);
            }
            String subject = null;
            String body = null;
            if (BusinessTypeEnum.SOLUTION.getDbValue() == order.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(order.getBusinessId());
                if (solution == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不存在！"), null);
                }
                if (solution.getStatus().intValue() != SolutionStateEnum.SHELVE.getDbValue()) {
                    return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该方案不是上架状态！"), null);
                }
//				if(SOLUTION.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == order.getBusinessType().intValue()) {
                Specification specification = specificationService.getSpecification(order.getBusinessId());
                if (specification == null) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范不存在！"), null);
                }
                if (specification.getStatus().intValue() != SpecificationStatus.SHELVE.getDbValue()) {
                    return ResultData
                            .newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "该行业规范不是上架状态！"), null);
                }
//				if(specification.getCharges().compareTo(order.getAmount()) !=0){
//					throw new SCInvalidParamException("付款金额和收费金额不匹配");
//				}
                subject = "方案馆--" + order.getBusinessId();
                body = " 编号：" + order.getBusinessName();
            } else {
                return ResultData.newInstance(new Meta(ReturnCode.TARGET_NOT_FOUND.getValue(), "订单信息不正确！"), null);
            }
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("OrderIds", userPayRequestBean.getTradeNo());
            paraMap.put("Amount", order.getAmount().toString());
            paraMap.put("Type", userPayRequestBean.getPayMode() + "");
            paraMap.put("AccountId", order.getUid() + "");
            paraMap.put("OperatorId", order.getUid() + "");
            paraMap.put("Subject", subject);
            paraMap.put("Body", body);
            userPayOrderService.updatePayModel(order.getOrderNo(), userPayRequestBean.getPayMode());

            String resultJson = paymentService.wxPayPc(paraMap);
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "返回微信支付信息成功！"),
                    new PaymentResponseBean(resultJson, paraMap.get("OrderIds")));
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "payDepositAmount");
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), errMsg), null);
        }
    }

    public ResultData addPayOrder(UserPayOrderRequestBean payOrderRequestBean) {
        try {
            logger.info(String.format("%s param:%s", "aliPay", payOrderRequestBean.toJson()));
            if (payOrderRequestBean == null) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数不正确"), null);
            }
            if (
                    !NumberHelper.validatePositive(payOrderRequestBean.getBusinessType()) ||
                            !NumberHelper.validatePositive(payOrderRequestBean.getUserId())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数不正确"), null);
            }
            if (!BusinessTypeEnum.dbValueExist(payOrderRequestBean.getBusinessType())) {
                return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "参数不正确"), null);
            }
            UserOrderResponseBean orderResponse = new UserOrderResponseBean();
            Long bizId = Long.valueOf(payOrderRequestBean.getBusinessId());
            if (BusinessTypeEnum.SOLUTION.getDbValue() == payOrderRequestBean.getBusinessType().intValue()) {
                Solution solution = solutionService.getSolution(Long.valueOf(payOrderRequestBean.getBusinessId()));
                if (solution == null || !SolutionStateEnum.SHELVE.getDbValue().equals(solution.getStatus())) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案已经下架了"), null);
                }
                if (solution.getIsFree().intValue() == 0) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该方案不收费"), null);
                }
				/*if(SOLUTION.getCharges().compareTo(payOrderRequestBean.getAmount()) !=0){
					return ResponseBuilder.build(ReturnCode.FAILURE,"付款金额和收费金额不匹配", null);
				}*/
                if (solution.getUserId().equals(payOrderRequestBean.getUserId())) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户为该方案上传用户"), null);
                }
                UserPayOrder userPayOrder = userPayOrderService.queryUserPayOrder(Long.valueOf(payOrderRequestBean
                                .getBusinessId()),
                        payOrderRequestBean.getUserId());

                if (userPayOrder == null) {
                    UserPayOrder addUserPayOrder = new UserPayOrder();
                    addUserPayOrder.setBusinessId(Long.valueOf(payOrderRequestBean.getBusinessId()));
                    addUserPayOrder.setBusinessType(BusinessTypeEnum.SOLUTION.getDbValue());
                    addUserPayOrder.setUid(payOrderRequestBean.getUserId());
                    addUserPayOrder.setAmount(payOrderRequestBean.getAmount());
                    String order = paymentService.handlePayAmount(addUserPayOrder);
                    orderResponse.setOrderNo(order);
                    orderResponse.setBusinessId(Long.valueOf(payOrderRequestBean.getBusinessId()));
                    orderResponse.setBusinessType(payOrderRequestBean.getBusinessType());
                    orderResponse.setAmount(payOrderRequestBean.getAmount());
                    orderResponse.setUid(payOrderRequestBean.getUserId());
                    orderResponse.setStatus(PayStateEnum.WAITTOPAY.getDbValue());
                } else {
                    if (userPayOrder.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                        return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "已经支付成功,无需再支付"), null);
                    }
                    if (payOrderRequestBean.getAmount().compareTo(userPayOrder.getAmount()) != 0) {
                        //修改订单金额
                        userPayOrder.setAmount(payOrderRequestBean.getAmount());
                        userPayOrderService.updateOrder(userPayOrder);
                    }
                    orderResponse.setOrderNo(userPayOrder.getOrderNo().toString());
                    orderResponse.setBusinessId(Long.valueOf(payOrderRequestBean.getBusinessId()));
                    orderResponse.setBusinessType(payOrderRequestBean.getBusinessType());
                    orderResponse.setAmount(payOrderRequestBean.getAmount());
                    orderResponse.setUid(userPayOrder.getUid());
                    orderResponse.setStatus(userPayOrder.getStatus());
                }
                //行业规范
            } else if (BusinessTypeEnum.SPECIFICATION.getDbValue() == payOrderRequestBean.getBusinessType()
                    .intValue()) {
                Specification specification = specificationService.getSpecification(Long.valueOf(payOrderRequestBean
                        .getBusinessId()));
                if (specification == null || !SpecificationStatus.SHELVE.getDbValue()
                        .equals(specification.getStatus())) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范已经下架"), null);
                }
                if (specification.getCharges().compareTo(BigDecimal.ZERO) != 1) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "该行业规范已支持免费下载"), null);
                }
				/*if(specification.getCharges().compareTo(payOrderRequestBean.getAmount()) !=0){
					return ResponseBuilder.build(ReturnCode.FAILURE,"付款金额和收费金额不匹配", null);
				}*/
                if (specification.getUserId().equals(payOrderRequestBean.getUserId())) {
                    return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "当前用户为该方案上传用户"), null);
                }
                UserPayOrder userPayOrder = userPayOrderService
                        .queryUserPayOrder(bizId, payOrderRequestBean.getUserId());
                if (userPayOrder == null) {
                    UserPayOrder addUserPayOrder = new UserPayOrder();
                    addUserPayOrder.setBusinessId(bizId);
                    addUserPayOrder.setBusinessType(BusinessTypeEnum.SPECIFICATION.getDbValue());
                    addUserPayOrder.setUid(payOrderRequestBean.getUserId());
                    addUserPayOrder.setAmount(payOrderRequestBean.getAmount());
                    String order = paymentService.handlePayAmount(addUserPayOrder);
                    orderResponse.setOrderNo(order);
                    orderResponse.setBusinessId(bizId);
                    orderResponse.setBusinessType(payOrderRequestBean.getBusinessType());
                    orderResponse.setAmount(payOrderRequestBean.getAmount());
                    orderResponse.setUid(payOrderRequestBean.getUserId());
                    orderResponse.setStatus(PayStateEnum.WAITTOPAY.getDbValue());
                } else {
                    if (userPayOrder.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                        return ResultData.newInstance(new Meta(ReturnCode.FAILURE.getValue(), "已经支付成功,无需再支付"), null);
                    }
                    if (payOrderRequestBean.getAmount().compareTo(userPayOrder.getAmount()) != 0) {
                        //修改订单金额
                        userPayOrder.setAmount(payOrderRequestBean.getAmount());
                        userPayOrderService.updateOrder(userPayOrder);
                    }
                    orderResponse.setOrderNo(userPayOrder.getOrderNo().toString());
                    orderResponse.setBusinessId(bizId);
                    orderResponse.setBusinessType(payOrderRequestBean.getBusinessType());
                    orderResponse.setAmount(payOrderRequestBean.getAmount());
                    orderResponse.setUid(userPayOrder.getUid());
                    orderResponse.setStatus(userPayOrder.getStatus());
                }
            }
            return ResultData.newInstance(new Meta(ReturnCode.SUCCEED.getValue(), "生成支付订单成功"), orderResponse);
        } catch (Exception e) {
            String errMsg = String.format("%s系统错误", "addPayOrder");
            logger.error(errMsg, e);
            return ResultData.newInstance(new Meta(ReturnCode.SYS_ERR.getValue(), errMsg), null);
        }
    }
}
